﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Menu;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Menu
{
    public class UpdatePathHandler : IRequestHandler<UpdatePathCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PathModel> _menuRepository;
        private readonly IMapper _mapper;

        public UpdatePathHandler(IBaseRepository<PathModel> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdatePathCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var menuname = _menuRepository.GetAll().FirstOrDefault(p => p.MenuName == request.MenuName && p.Id != request.Id && p.PartentId == request.PartentId);
            if (menuname != null)
            {
                result.Code = StatusEnum.Fail;
                result.Message = "菜单名称已存在";
                return Task.FromResult(result);
            }
            var menu = _menuRepository.GetAll().Where(p => p.Id == request.Id).FirstOrDefault();
            if (menu != null)
            {
                menu = _mapper.Map(request, menu);
                menu.UpdateTime = DateTime.Now;
                menu.Updater = "李四";
            }
            var res = _menuRepository.Update(menu);
            if (res > 0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "修改成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "修改失败";

            }

            return Task.FromResult(result);
        }
    }
}
